package com.tnovoselec.server.news.worker;

import java.io.File;
import java.io.FileWriter;
import java.io.StringWriter;
import java.util.Iterator;
import java.util.List;
import java.util.TimerTask;

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import com.tnovoselec.server.news.Config;
import com.tnovoselec.server.news.beans.BugItem;
import com.tnovoselec.server.news.beans.DvadesetCetiriSataItem;
import com.tnovoselec.server.news.beans.IItem;
import com.tnovoselec.server.news.beans.JutarnjiItem;
import com.tnovoselec.server.news.beans.TportalItem;
import com.tnovoselec.server.news.util.XMLUtil;

public class RefreshNews extends TimerTask {

	IItem activeitem;
	Document mainDoc;
	Element root;

	@Override
	public void run() {
		try {
			mainDoc = XMLUtil.getEmptyDoc();
			root = XMLUtil.createElement(mainDoc, "root", null);
			
			parse();
			
			mainDoc.appendChild(root);
			mainDoc.normalize();
			saveXML(mainDoc, "main", "");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void parse() {
		parseJutarnji();
		parseBug();
		parseDvadesetCetiriSata();
		parseTportal();
	}

	private void parseJutarnji() {
		
		Element jutarnji = XMLUtil.createElement(mainDoc, "channel", root);
		XMLUtil.addAttirbute(jutarnji, "name", "Jutarnji List");
		XMLUtil.addAttirbute(jutarnji, "icon", Config.SERVER_IMAGES_PREFIX + "j.png");
		activeitem = new JutarnjiItem();

		RSSParser parser;

		Iterator<String> iterator = Config.jutarnjiRSSLinks.keySet().iterator();

		while (iterator.hasNext()) {
			
			String channelName = iterator.next();
			String url = Config.jutarnjiRSSLinks.get(channelName);
			
			Element item = XMLUtil.createElement(mainDoc, "item", jutarnji);
			XMLUtil.addAttirbute(item, "name", channelName);
			XMLUtil.addAttirbute(item, "url", Config.SERVER_URL_PREFIX + "jutarnji/" + channelName + ".xml");
			
			parser = new RSSParser(url, activeitem);
			parser.parse();
			List<IItem> items = parser.getItems();
			buildXML(channelName, items, "jutarnji");
		}

	}

	private void parseBug() {
		Element bug = XMLUtil.createElement(mainDoc, "channel", root);
		XMLUtil.addAttirbute(bug, "name", "Bug Online");
		XMLUtil.addAttirbute(bug, "icon", Config.SERVER_IMAGES_PREFIX + "bug.png");
		activeitem = new BugItem();
		RSSParser parser;
		Iterator<String> iterator = Config.bugRSSLinks.keySet().iterator();
		while (iterator.hasNext()) {
			String channelName = iterator.next();
			String url = Config.bugRSSLinks.get(channelName);
			
			Element item = XMLUtil.createElement(mainDoc, "item", bug);
			XMLUtil.addAttirbute(item, "name", channelName);
			XMLUtil.addAttirbute(item, "url",  Config.SERVER_URL_PREFIX + "bug/" + channelName + ".xml");
			
			parser = new RSSParser(url, activeitem);
			parser.parse();
			List<IItem> items = parser.getItems();
			buildXML(channelName, items, "bug");
		}
	}

	private void parseDvadesetCetiriSata() {
		
		Element dvadesetcetirisata = XMLUtil.createElement(mainDoc, "channel", root);
		XMLUtil.addAttirbute(dvadesetcetirisata, "name", "24 sata");
		XMLUtil.addAttirbute(dvadesetcetirisata, "icon", Config.SERVER_IMAGES_PREFIX + "dd.png");
		activeitem = new DvadesetCetiriSataItem();
		RSSParser parser;
		Iterator<String> iterator = Config.dvadesetCetiriSataRSSLinks.keySet().iterator();
		while (iterator.hasNext()) {
			String channelName = iterator.next();
			String url = Config.dvadesetCetiriSataRSSLinks.get(channelName);
			
			Element item = XMLUtil.createElement(mainDoc, "item", dvadesetcetirisata);
			XMLUtil.addAttirbute(item, "name", channelName);
			XMLUtil.addAttirbute(item, "url",  Config.SERVER_URL_PREFIX + "dvadesetCetiriSata/" + channelName + ".xml");
			
			
			parser = new RSSParser(url, activeitem);
			parser.parse();
			List<IItem> items = parser.getItems();
			buildXML(channelName, items, "dvadesetCetiriSata");
		}
	}

	private void parseTportal() {
		Element tportal = XMLUtil.createElement(mainDoc, "channel", root);
		XMLUtil.addAttirbute(tportal, "name", "Tportal");
		XMLUtil.addAttirbute(tportal, "icon", Config.SERVER_IMAGES_PREFIX + "t.png");
		activeitem = new TportalItem();
		RSSParser parser;
		Iterator<String> iterator = Config.tportalRSSLinks.keySet().iterator();
		while (iterator.hasNext()) {
			String channelName = iterator.next();
			String url = Config.tportalRSSLinks.get(channelName);
			
			Element item = XMLUtil.createElement(mainDoc, "item", tportal);
			XMLUtil.addAttirbute(item, "name", channelName);
			XMLUtil.addAttirbute(item, "url", Config.SERVER_URL_PREFIX + "tportal/" + channelName + ".xml");
			
			
			parser = new RSSParser(url, activeitem);
			parser.parse();
			List<IItem> items = parser.getItems();
			buildXML(channelName, items, "tportal");
		}
	}

	private void buildXML(String channelName, List<IItem> items, String provider) {
		Document doc;
		try {
			doc = XMLUtil.getEmptyDoc();
			Element root = XMLUtil.createElement(doc, "root", null);
			XMLUtil.createElement(doc, "channelName", channelName, root);
			Element itemsEl = XMLUtil.createElement(doc, "items", root);
			for (IItem item : items) {
				Element itemEl = XMLUtil.createElement(doc, "item", itemsEl);
				XMLUtil.createElement(doc, "title", item.getTitle(), itemEl);
				XMLUtil.createElement(doc, "pubDate", item.getPubDate(), itemEl);
				XMLUtil.createElement(doc, "description", item.getDescription(), itemEl);
				XMLUtil.createElement(doc, "link", item.getLink(), itemEl);
				Element images = XMLUtil.createElement(doc, "images", itemEl);
				for (String imageurl : item.getImages()) {
					XMLUtil.createElement(doc, "image", imageurl, images);
				}
			}
			doc.appendChild(root);
			doc.normalize();
			saveXML(doc, channelName, provider);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void saveXML(Document doc, String channelName, String provider) {
		System.out.println(channelName);
		if (doc == null || channelName == null) {
			return;
		}

		try {
	//		File f = new File("./war/xmls/" + provider + "/" + channelName + ".xml");
		File f = new File("/usr/local/NewsServer/server/war/xmls/" + provider + "/" + channelName + ".xml");
			FileWriter fw = new FileWriter(f);
			DOMSource domSource = new DOMSource(doc);
			StringWriter writer = new StringWriter();
			StreamResult result = new StreamResult(writer);
			TransformerFactory tf = TransformerFactory.newInstance();
			Transformer transformer = tf.newTransformer();
			transformer.transform(domSource, result);
			String content = new String(writer.toString().getBytes(), "UTF-8");
			fw.write(content);
			fw.flush();
			fw.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
